using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NorthwindWeb.Models;

namespace NorthwindWeb.Controllers
{   
    public class CategoryController : Controller
    {
		private readonly ICategoryRepository categoryRepository;

		// If you are using Dependency Injection, you can delete the following constructor
        public CategoryController() : this(new CategoryRepository())
        {
        }

        public CategoryController(ICategoryRepository categoryRepository)
        {
			this.categoryRepository = categoryRepository;
        }

        //
        // GET: /Category/

        public ViewResult Index()
        {
            return View(categoryRepository.AllIncluding(category => category.Products));
        }


        //
        // POST: /Category/Create

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "CategoryID")]Category category)
        {
            if (ModelState.IsValid) {
                categoryRepository.InsertOrUpdate(category);
                categoryRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }
        
        //
        // POST: /Category/Edit/5

        [HttpPost]
        public ActionResult Edit(Category category)
        {
            if (ModelState.IsValid) {
                categoryRepository.InsertOrUpdate(category);
                categoryRepository.Save();
                return RedirectToAction("Index");
            } else {
                return RedirectToAction("Index");
            }
        }

        //
        // POST: /Category/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            categoryRepository.Delete(id);
            categoryRepository.Save();

            return RedirectToAction("Index");
        }

        
        public JsonResult categoryGridData(int rows, int page)
        {
        	var count = categoryRepository.All.Count();
            var pageData = categoryRepository.All.OrderBy(x => x.CategoryID).Skip((page - 1) * rows).Take(rows).Select(o => new {CategoryID = o.CategoryID, CategoryName = o.CategoryName, Description = o.Description});
            return Json(new { 
            page = page,
            records = count,
            rows = pageData,
            total = Math.Ceiling((decimal)count / rows)
            }, JsonRequestBehavior.AllowGet);
        }
        
        
    }
}

